package com.example.guiguiapplicatio.fragment.record;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.donkingliang.labels.LabelsView;
import com.example.guiguiapplicatio.api.GetdataResponseBody.getsigningidendtimeApi;
import com.example.guiguiapplicatio.api.Interface.AllCallback;
import com.example.guiguiapplicatio.api.Interface.GetSigningendCallback;
import com.example.guiguiapplicatio.api.RecordDetailApi;
import com.example.guiguiapplicatio.R;
import com.example.guiguiapplicatio.Response.Signing;
import com.example.guiguiapplicatio.databinding.FragmentTotalDetailBinding;
import com.example.guiguiapplicatio.util.ResponseBody;
import com.example.guiguiapplicatio.utils.ApiUtils;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class RecordDetailFragment extends Fragment implements AllCallback {
    FragmentTotalDetailBinding binding;
    private LabelsView labelsView;
    private static final String ARG_ID_CARD = "idCard";
    private String idCard;
    private String name1;
    private getsigningidendtimeApi getsigningidendtimeApi;
    private RecordDetailApi recordDetailApi;
    ApiUtils apiUtils;
    int select = 1; //表示单选对话框初始时选中哪一项
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            idCard = getArguments().getString(ARG_ID_CARD);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentTotalDetailBinding.inflate(inflater, container, false);
        View view = binding.getRoot();
        String baseUrl = getString(R.string.api);
        apiUtils = new ApiUtils(baseUrl);
        recordDetailApi = new RecordDetailApi();
        recordDetailApi.setallCallback(this);
        recordDetailApi.performRecordDetail(idCard);
        binding.servicBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().onBackPressed();
            }
        });
        binding.healthRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("idCard", idCard);
                Navigation.findNavController(v).navigate(R.id.action_recordDetailFragment_to_totalDetailHealthFragment, bundle);
            }
        });


        binding.signingManage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("idCard", idCard);
                Navigation.findNavController(v).navigate(R.id.action_recordDetailFragment_to_FulfillmenthomeFragment, bundle);
            }
        });
        binding.doctorSigning.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

//                final String[] items = {"个人签约", "家庭签约"};
//                AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
//                dialog.setTitle("选择签约类型")
//                        .setItems(items, new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                Toast.makeText(getContext(), items[which].toString(), Toast.LENGTH_SHORT).show();
//                            }
//                        })
//                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                dialog.dismiss();
//                            }
//                        });
//                dialog.show();
                Bundle bundle = new Bundle();
                bundle.putString("idCard", idCard);
                Navigation.findNavController(v).navigate(R.id.action_recordDetailFragment_to_SigningArchivesFragment, bundle);
            }
        });
        binding.familyRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("idCard", idCard);
                recordDetailApi = new RecordDetailApi();
                recordDetailApi.setallCallback(new AllCallback() {
                    @Override
                    public void onSuccess(ResponseBody<Object> responseBody) throws ParseException {
                        JsonObject jsonObject = JsonParser.parseString(responseBody.getData().toString()).getAsJsonObject();
                        JsonElement typeElement = jsonObject.get("type");
                        Log.d("typeElement", String.valueOf(typeElement));
                        if(String.valueOf(typeElement).equals("0")){
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    AlertDialog dialog=new AlertDialog.Builder(getContext())
                                            .setTitle("家庭档案")//设置标题
                                            .setMessage("您是否要建立一个家庭")//设置要显示的内容
                                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialogInterface, int i) {
                                                    dialogInterface.dismiss();//销毁对话框
                                                }
                                            })
                                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    getsigningidendtimeApi = new getsigningidendtimeApi();
                                                    getsigningidendtimeApi.setallCallback(new GetSigningendCallback() {
                                                        @Override
                                                        public void onSuccess(ResponseBody<Signing> responseBody) throws ParseException {
                                                            if(responseBody != null && responseBody.getData() != null){
                                                                getActivity().runOnUiThread(new Runnable() {
                                                                    @Override
                                                                    public void run() {
                                                                        Toast.makeText(getContext(), "已签约不能建立家庭档案", Toast.LENGTH_SHORT).show();
                                                                    }
                                                                });
                                                            }else {
                                                                Call<Object> objectCall = apiUtils.getApi().addNewFamilyarChives(idCard);
                                                                objectCall.clone().enqueue(new Callback<Object>() {
                                                                    @Override
                                                                    public void onResponse(Call<Object> call, Response<Object> response) {
                                                                        if(response.code() == 200){
                                                                            getActivity().runOnUiThread(() -> {
                                                                                Toast.makeText(getContext(), "创建成功", Toast.LENGTH_LONG).show();
                                                                                Navigation.findNavController(v).navigate(R.id.action_recordDetailFragment_to_FamilyArchivesFragment, bundle);
                                                                            });
                                                                        }
                                                                    }

                                                                    @Override
                                                                    public void onFailure(Call<Object> call, Throwable t) {

                                                                    }
                                                                });
                                                            }
                                                        }

                                                        @Override
                                                        public void onFailure(String errorMessage) {

                                                        }
                                                    });
                                                    getsigningidendtimeApi.performgetsigningidendtime(idCard);
                                                    dialog.dismiss();
                                                }
                                            }).create();//create（）方法创建对话框
                                    dialog.show();//显示对话框
                                }
                            });
                        }
                        else {
                            bundle.putString("typeElement", String.valueOf(typeElement));
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Navigation.findNavController(v).navigate(R.id.action_recordDetailFragment_to_FamilyArchivesFragment, bundle);
                                }
                            });
                        }
                    }

                    @Override
                    public void onFailure(String errorMessage) {

                    }
                });
                recordDetailApi.performRecordDetailMain(idCard);
            }
        });

        recordReportBtnSet();

        return view;
    }

    private void recordReportBtnSet() {//设置随访报告跳转
        binding.suifangRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (idCard != null && idCard != "") {
                    Bundle bundle = new Bundle();
                    bundle.putString("idCard", idCard);
                    Navigation.findNavController(v).navigate(R.id.action_recordDetailFragment_to_followUpRecordClassifyFragment, bundle);
                }
            }
        });
    }

    @Override
    public void onResume() {
        BottomNavigationView bottomNavigationView = requireActivity().findViewById(R.id.nav_view);
        bottomNavigationView.setVisibility(View.INVISIBLE);
        //这两行代码设置隐藏底部导航栏，若要显示啧修改INVISIBLE为Visible（可见）

        binding.healthTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("idCard", idCard);
                bundle.putString("name", name1);
                Navigation.findNavController(v).navigate(R.id.action_recordDetailFragment_to_examinationPersonFragment, bundle);
            }
        });
        super.onResume();
    }

    @Override
    public void onSuccess(ResponseBody<Object> responseBody) {
        if (responseBody != null && responseBody.getData() != null) {
            // 解析JSON字符串为JsonObject
            JsonObject jsonObject = JsonParser.parseString(responseBody.getData().toString()).getAsJsonObject();
//                Log.d("info", "我在这里" + jsonObject.toString());
                String name = jsonObject.get("name").getAsString();
                name1=name;
                String sex = jsonObject.get("sex").getAsString();
                int age = jsonObject.get("age").getAsInt();
                String phone = jsonObject.get("phone").getAsString();
                String detailedresidence = jsonObject.get("detailedresidence").getAsString();
                List<String> listenername = new ArrayList<>();
                if (jsonObject.has("listenername")) {
                    JsonArray listenernameArray = jsonObject.getAsJsonArray("listenername");
                    for (JsonElement element : listenernameArray) {
                        listenername.add(element.getAsString());
                    }
                } else {
                    Log.d("info", "'listenername'字段不存在");
                }

                if (getActivity()!=null){
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // 在这里更新 UI 视图
                            binding.recordName.setText(name);
                            binding.recordAge.setText(String.valueOf(age));
                            binding.recordSex.setText(sex);
                            binding.recordPhone.setText(phone);
                            binding.recordDetailedresidence.setText(detailedresidence);
                            labelsView = (LabelsView)binding.labels;
                            labelsView.setLabels(listenername);
                        }
                    });

                }

        }else {
            Log.d("info","responseBody"+ responseBody.toString());
        }
    }

    @Override
    public void onFailure(String errorMessage) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getContext(), "档案详情响应失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

}